package com.jd.org.service.impl;

import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.org.domain.Department;
import com.jd.org.mapper.DepartmentMapper;
import com.jd.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> deptTree() {
        //将所有的部门添加的Map中 - 为了根据id去获取
        List<Department> departments = departmentMapper.loadAll();
        Map<Long, Department> map = new HashMap<>();
        // 将部门的id和对象保存在map中
        for (Department department : departments) {
            map.put(department.getId(), department);
        }
        // 查询部门树
        List<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            // 如果没有父id-顶级部门
            if (department.getParent_id() == null) {
                deptTree.add(department);
            } else {
                // 获取父部门id
                Long parent_id = department.getParent_id();
                // 获取父部门
                Department parentDept = map.get(parent_id);
                if (parentDept != null) {
                    // 将自己添加到父部门的children中
                    parentDept.getChildren().add(department);
                }
            }

        }
        return deptTree;
    }
}

